package com.java.utils;

import java.util.Calendar;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class EmailUtils {
	public static void sendMessage(String recevice,String title,String content,final String email,final String psw) {
		// 第一步：配置javax.mail.Session对象
		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.qq.com");
		props.put("mail.smtp.starttls.enable", "true");// 使用 STARTTLS安全连接
		props.put("mail.smtp.auth", "true"); // 使用验证
		Session mailSession = Session.getInstance(props, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				// TODO Auto-generated method stub
				return new PasswordAuthentication(email,
						psw);
			}

		});
		mailSession.setDebug(true);
		// 第二步：编写消息
		try {
			InternetAddress fromAddress = new InternetAddress(email);
			InternetAddress toAddress = new InternetAddress(recevice);

			MimeMessage message = new MimeMessage(mailSession);

			message.setFrom(fromAddress);
			message.addRecipient(RecipientType.TO, toAddress);

			message.setSentDate(Calendar.getInstance().getTime());
			message.setSubject(title);
			message.setContent(content, "text/html;charset=utf-8");

			// 第三步：发送消息
			Transport transport = mailSession.getTransport("smtp");
			transport.connect(mailSession.getProperty("mail.smtp.host"),
					email, psw);
			Transport.send(message, message.getRecipients(RecipientType.TO));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
